﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Common.Lists;
using DNNToolkit.Modules.FAQ.Components;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;

namespace DNNToolkit.Modules.FAQ
{
    public partial class EditFAQ : PortalModuleBase,IActionable
    {
        private readonly FAQController _controller=new FAQController();

        #region Event Handlers

        private void PopulateCategories()
        {
            mCategoryCheckBoxs.Items.Clear();
            foreach (var category in _controller.GetAllFAQCategoryDefinitions())
            {
                mCategoryCheckBoxs.Items.Add(new ListItem(category.CategoryName,category.CategoryDefinitionID.ToString()));    
            }
        }

        private long FAQID
        {
            get
            {
                if (ViewState["FAQID"] != null)
                    return Convert.ToInt64(ViewState["FAQID"]);
                return 0L;
            }
            set
            {
                ViewState["FAQID"] = value;
            }
        }

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    PopulateCategories();
                    if (Request.Params["FAQID"] != null)
                    {
                        FAQID = Convert.ToInt64(Request.Params["FAQID"]);
                        
                        FAQInfo objFAQ = _controller.GetFAQ(FAQID,this.ModuleId);
                        PopulateFAQ(objFAQ);
                    }
                }
                cmdDelete.Visible = (FAQID!=0);                    
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// Populates the FAQ.
        /// </summary>
        /// <param name="objFAQ">The obj FAQ.</param>
        private void PopulateFAQ(FAQInfo objFAQ)
        {
            if (objFAQ.FAQCategoryInfo != null)
            {
                foreach (var category in objFAQ.FAQCategoryInfo)
                {
                    foreach (ListItem item in mCategoryCheckBoxs.Items)
                    {
                        if (item.Value == category.CategoryDefinitionID.ToString())
                        {
                            item.Selected = true;
                            break;
                        }
                    }
                }
            }
            mAnswerTextBox.Text = objFAQ.AnswerRichText;
            mQuestionTextBox.Text = objFAQ.QuestionRichText;
        }

        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// Validates the data.
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            mQuestionValidator.Visible = false;
            mAnswerValidator.Visible = false;
            mCategoryValidator.Visible = false;
            if (string.IsNullOrEmpty(mQuestionTextBox.Text))
            {
                mQuestionValidator.Visible = true;
                return false;
            }
            if (string.IsNullOrEmpty(mAnswerTextBox.Text))
            {
                mAnswerValidator.Visible = true;
                return false;
            }
            bool isValid = false;
            foreach (ListItem item in mCategoryCheckBoxs.Items)
            {
                if (item.Selected)
                {
                    isValid = true;
                    break;
                }
            }
            if (!isValid)
                mCategoryValidator.Visible = true;
            return isValid;
        }

        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            if (!ValidateData())
            {
                return;
            }
            try
            {
               
                FAQInfo objFAQ = new FAQInfo();
                if (FAQID > 0)
                    objFAQ = _controller.GetFAQ(FAQID,ModuleId);
                objFAQ=SaveFAQ(objFAQ);
                if (objFAQ.FAQID > 0)
                {
                    _controller.UpdateFAQ(objFAQ);
                }
                else
                    _controller.CreateFAQ(objFAQ);
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private FAQInfo SaveFAQ(FAQInfo objFAQ)
        {
            var list = new List<FAQCategoryDefinitionInfo>();
            foreach (ListItem item in mCategoryCheckBoxs.Items)
            {
                if (item.Selected)
                    objFAQ.FAQCategoryInfo.Add(new FAQCategoryInfo() { CategoryDefinitionID=long.Parse(item.Value)});
            }
            
            objFAQ.ModuleID = this.ModuleId;
            objFAQ.Answer = mAnswerTextBox.Text;
            objFAQ.AnswerRichText = mAnswerTextBox.Text;
            objFAQ.Question = mQuestionTextBox.Text;
            objFAQ.QuestionRichText = mQuestionTextBox.Text;
            objFAQ.FAQID = FAQID;
            return objFAQ;
        }


        /// <summary>
        /// Handles the Click event of the cmdDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void cmdDelete_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                FAQInfo objFAQ = _controller.GetFAQ(FAQID,ModuleId);
                _controller.DeleteFAQ(objFAQ);
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion


        #region IActionable Members


        /// <summary>
        /// Gets the module actions.
        /// </summary>
        /// <value>The module actions.</value>
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString("Content.Action", this.LocalResourceFile), ModuleActionType.AddContent, "", "view.gif", Globals.NavigateURL(), false, SecurityAccessLevel.Edit, true, false);
                Actions.Add(this.GetNextActionID(), Localization.GetString("ContentOptions.Action", this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl("EditCategory"), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion
    }
}